<template>
  <ContentWrap> 
    <!-- 搜索表单 -->
      <el-form 
        class="-mb-15px"
        :inline="true" 
        :model="searchForm"
        ref="queryFormRef"
        label-width="68px"
      >
        <el-form-item prop="bomName">
          <el-input 
            v-model="searchForm.bomName" 
            placeholder="请输入BOM名称" 
            clearable
            @keyup.enter="handleQuery"
            class="!w-240px" 
          />
        </el-form-item>
        
        <el-form-item prop="productInfo">
          <el-input 
            v-model="searchForm.productInfo" 
            placeholder="请输入产品名称/编号" 
            clearable
            @keyup.enter="handleQuery"
            class="!w-240px"
          />
        </el-form-item>
        
        <el-form-item prop="productCategory">
          <el-input 
            v-model="searchForm.productCategory" 
            placeholder="请输入产品分类" 
            clearable
            @keyup.enter="handleQuery"
            class="!w-240px"
          />
        </el-form-item>
        
        <el-form-item prop="documentStatus">
          <el-select 
            v-model="searchForm.documentStatus" 
            placeholder="请选择单据状态" 
            clearable
            @keyup.enter="handleQuery"
            class="!w-240px"
          >
            <el-option label="全部" value="" />
            <el-option label="草稿" value="draft" />
            <el-option label="已审核" value="approved" />
          </el-select>
        </el-form-item>
        
        <el-form-item prop="reviewStatus">
          <el-select 
            v-model="searchForm.reviewStatus" 
            placeholder="请选择审核状态" 
            clearable
            @keyup.enter="handleQuery"
            class="!w-240px"
          >
            <el-option label="全部" value="" />
            <el-option label="待审核" value="pending" />
            <el-option label="已通过" value="passed" />
            <el-option label="已拒绝" value="rejected" />
          </el-select>
        </el-form-item>
        
        <el-form-item prop="lastUpdater">
          <el-input 
            v-model="searchForm.lastUpdater" 
            placeholder="请输入最后更新人" 
            clearable
            @keyup.enter="handleQuery"
            class="!w-240px"
          />
        </el-form-item>
        
        <el-form-item prop="customerName">
          <el-input 
            v-model="searchForm.customerName" 
            placeholder="请输入客户名称" 
            clearable
            @keyup.enter="handleQuery"
            class="!w-240px"
          />
        </el-form-item>

        <el-form-item prop="property">
          <el-input 
            v-model="searchForm.property" 
            placeholder="请输入属性" 
            clearable
            @keyup.enter="handleQuery"
            class="!w-240px"
          />
        </el-form-item>

        <el-form-item prop="specification">
          <el-input 
            v-model="searchForm.specification" 
            placeholder="请输入规格" 
            clearable
            @keyup.enter="handleQuery"
            class="!w-240px"
          />
        </el-form-item>

        <el-form-item>
          <el-button @click="handleQuery"><Icon icon="ep:search" class="mr-5px" />搜索</el-button>
          <el-button @click="handleReset"><Icon icon="ep:refresh" class="mr-5px" />重置</el-button>
        </el-form-item>
        
      </el-form>
    </ContentWrap>  
    <!-- 操作按钮区域 -->
    

    <!-- 表格区域 -->

      <el-row :gutter="10" style="margin-bottom: 16px">
        <el-col :span="12">
          <div class="operation-buttons">
            <el-button type="primary" plain @click="openForm('create')">
              新增
            </el-button>
            <el-button type="default" @click="handleDelete" :disabled="!selectedRows.length">
              删除
            </el-button>
            <!-- <el-button type="default" @click="handleApprove" :disabled="!selectedRows.length">
              审核
            </el-button>
            <el-button type="default" @click="handleReject" :disabled="!selectedRows.length">
              反审核
            </el-button> -->
            <el-button @click="handleImport">
              批量导入
            </el-button>
            <el-button @click="handleExport">
              批量导出
            </el-button>
          </div>
        </el-col>
        <el-col :span="12" style="display: flex; justify-content: flex-end">
          <div style="text-align: right" >
            <el-button type="default" plain @click="btnLie">
              <img key="1" alt="" width="25px" height="20px" src="@/assets/svgs/column.svg" />
              列表字段
            </el-button>
          </div>
        </el-col>
      </el-row>
      <el-table
        :data="tableData"
        border
        style="width: 100%"
        :stripe="true"
        :show-overflow-tooltip="true"
        @selection-change="handleSelectionChange"
        v-loading="loading"
        
      >
        <el-table-column type="selection" label="选择" width="55" v-if="visibleColumns.selection" />
        <el-table-column label="序号" type="index" align="center" width="60" />
        <el-table-column prop="bomCode" label="BOM编号" width="150" align="center" v-if="visibleColumns.bomCode" />
        <el-table-column prop="standardBom" label="标准BOM" width="150" align="center" v-if="visibleColumns.reviewStatus1" >
          <template #default="{row}">
            <el-tag :type="row.standardBom === 'S' ? 'success' : 'info'">
              {{ row.standardBom }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="productName" label="产品名称"  width="150" align="center" v-if="visibleColumns.productName" />
        <el-table-column prop="productCode" label="产品编号" width="150" align="center" v-if="visibleColumns.productCode" />
        <el-table-column prop="customersName" label="客户名称" width="150" align="center" />
        <el-table-column prop="customerCode" label="客户编码" width="150" align="center" v-if="visibleColumns.customersName" />
        <el-table-column prop="guige" label="规格" width="80" align="center" v-if="visibleColumns.guige" />
        <el-table-column prop="shuxing" label="属性" width="80" align="center" v-if="visibleColumns.shuxing" />
        <el-table-column prop="image" label="产品图片" width="150" align="center" v-if="visibleColumns.image" />
        <el-table-column prop="prodectClassification" label="产品分类" width="150" align="center" v-if="visibleColumns.prodectClassification" />
        <el-table-column prop="documentStatus1" label="单据状态" width="150" align="center" v-if="visibleColumns.documentStatus1" />
        <el-table-column prop="reviewStatus1" label="审核状态" width="150" align="center" v-if="visibleColumns.reviewStatus1" />
        <el-table-column prop="founder" label="创建人" width="80" align="center"  v-if="visibleColumns.founder" />
        <el-table-column prop="date" label="创建时间" width="150" align="center"  v-if="visibleColumns.date" />
        <el-table-column prop="updateName" label="更新人" width="80" align="center"  v-if="visibleColumns.updateName" />
        <el-table-column prop="updateTime" label="更新时间" width="150" align="center" v-if="visibleColumns.updateTime" />
        <el-table-column label="操作" width="250" fixed="right" align="center" >
          <template #default="{row}">
            <el-button size="small" link @click="openForm('copy')">复制</el-button>
            <el-button size="small" link @click="openForm('detail')">详情</el-button>
            <el-button size="small" link :loading="exportLoading" @click="handleExportSingle">导出</el-button>
            <el-button 
              size="small" 
              link @click="handlePrint(row)"
            >
              打印
            </el-button>
          </template>
        </el-table-column>
      </el-table>
      
      <!-- 分页 -->
      <div class="pagination">
        <el-pagination
          v-model:current-page="pagination.currentPage"
          v-model:page-size="pagination.pageSize"
          :total="pagination.total"
          :page-sizes="[10, 20, 50, 100]"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>

    
    <!-- 新增/编辑对话框 -->
    <bom-edit-dialog
      v-model="dialogVisible"
      :form-data="currentBom"
      @submit="handleDialogSubmit"
    />
    <!-- 自定义字段 -->
  <el-dialog
    v-model="dialogVisible"
    title="自定义字段"
    width="50%"
    :before-close="handleClose"
  >
    <div class="content">
      <div class="content-tableData"><el-checkbox v-model="tempVisibleColumns.productName"  label="产品名称" size="large" /></div>
      <div class="content-tableData"><el-checkbox v-model="tempVisibleColumns.productCode"  label="产品编号" size="large" /></div>
      <div class="content-tableData"><el-checkbox v-model="tempVisibleColumns.customersName"  label="客户名称" size="large" /></div>
      <div class="content-tableData"><el-checkbox v-model="tempVisibleColumns.customerCode"  label="客户编码" size="large" /></div>
      <div class="content-tableData"><el-checkbox v-model="tempVisibleColumns.guige"  label="规格" size="large" /></div>
      <div class="content-tableData"><el-checkbox v-model="tempVisibleColumns.shuxing"  label="属性" size="large" /></div>
      <div class="content-tableData"><el-checkbox v-model="tempVisibleColumns.image"  label="产品图片" size="large" /></div>
      <div class="content-tableData"><el-checkbox v-model="tempVisibleColumns.prodectClassification"  label="产品分类" size="large" /></div>
      <div class="content-tableData"><el-checkbox v-model="tempVisibleColumns.documentStatus1"  label="单据状态" size="large" /></div>
      <div class="content-tableData"><el-checkbox v-model="tempVisibleColumns.reviewStatus1"  label="审核状态" size="large" /></div>
      <div class="content-tableData"><el-checkbox v-model="tempVisibleColumns.founder"  label="创建人" size="large" /></div>
      <div class="content-tableData"><el-checkbox v-model="tempVisibleColumns.date"  label="创建时间" size="large" /></div>
      <div class="content-tableData"><el-checkbox v-model="tempVisibleColumns.updateTime"  label="更新时间" size="large" /></div>
      <div class="content-tableData"><el-checkbox v-model="tempVisibleColumns.updateName"  label="更新人" size="large" /></div>
    </div>
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleConfirm">
          确定
        </el-button>
      </span>
    </template>
  </el-dialog>
  
  <AddBomDialog ref="formRef" @submit="handleDialogSubmit" />
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue'
import AddBomDialog from '@/views/erp/management/standardBOM/StandardBOMFrom.vue'
import download from '@/utils/download'
import { PurchaseReturnApi } from '@/api/erp/purchase/return'

const getList = async () => {
  loading.value = true
}

const exportLoading = ref(false) // 导出的加载中
// 搜索表单
const searchForm = reactive({
  bomName: '',
  productInfo: '',
  productCategory: '',
  documentStatus: '',
  reviewStatus: '',
  lastUpdater: '',
  customerName:'',
  property:'',
  specification:'',
  createTimeRange: []
})
const formRef = ref()
const openForm = (type: string, id?: number) => {
  formRef.value?.open(type, id)
};
const showAdvancedSearch = ref(false)
const loading = ref(false)
const tableData = ref([])
const selectedRows = ref([])
const dialogVisible = ref(false)
const currentBom = ref({})
const queryFormRef = ref() // 搜索的表单


const visibleColumns =ref({
  bomCode:true,
  selection:true,
  productName:true,
  productCode:true,
  customerCode:true,
  customersCode:true,
  customersName:true,
  guige:true,
  shuxing:true,
  image:true,
  prodectClassification:true,
  documentStatus1:true,
  reviewStatus1:true,
  founder:true,
  date:true,
  updateName:true,
  updateTime:true
})

// 分页
const pagination = reactive({
  currentPage: 1,
  pageSize: 10,
  total: 0
})
const tempVisibleColumns = ref({...visibleColumns.value})

// 列表字段确认选择
const handleConfirm = () => {
  visibleColumns.value = { ...tempVisibleColumns.value }
  dialogVisible.value = false
}
const btnLie = () => {
  tempVisibleColumns.value = {...visibleColumns.value}
  dialogVisible.value = true
}
// 模拟数据
const mockData = [{
    id: 1,
    bomCode: 'WLBOM20250001',
    standardBom: 'S',
    productName: '外壳',
    productCode: '1X-001-1',
    customersName: '客户A',
    prodectClassification: '分类1',
    documentStatus1: 'draft',
    reviewStatus1: 'pending',
    updateName: '张三'
  },
  {
    id: 2,
    bomCode: 'WLBOM20250002',
    standardBom: 'S',
    productName: '螺丝',
    productCode: '2X-002-1',
    customersName: '客户B',
    prodectClassification: '分类2',
    documentStatus1: 'approved',
    reviewStatus1: 'passed',
    updateName: '李四'
  }
]


// 初始化加载数据
onMounted(() => {
  fetchData()
})


/** 重置按钮操作 */
// const resetQuery = () => {
//   queryFormRef.value.resetFields()
//   handleQuery()
// }

// 获取数据
const fetchData = () => {
  loading.value = true
  // 模拟API请求
  // setTimeout(() => {
  //   tableData.value = mockData
  //   pagination.total = mockData.length
  //   loading.value = false
  // }, 500)
   setTimeout(() => {
    // 根据 searchForm 的条件过滤数据
    const filteredData = mockData.filter(item => {
      return (
        (searchForm.bomName === '' || item.bomCode.includes(searchForm.bomName)) &&
        (searchForm.productInfo === '' || 
          item.productName.includes(searchForm.productInfo) || 
          item.productCode.includes(searchForm.productInfo)) &&
        (searchForm.productCategory === '' || item.prodectClassification.includes(searchForm.productCategory)) &&
        (searchForm.documentStatus === '' || item.documentStatus1 === searchForm.documentStatus) &&
        (searchForm.reviewStatus === '' || item.reviewStatus1 === searchForm.reviewStatus) &&
        (searchForm.lastUpdater === '' || item.updateName.includes(searchForm.lastUpdater)) &&
        (searchForm.customerName === '' || item.customersName.includes(searchForm.customerName))
      );
    });
    tableData.value = filteredData;
    pagination.total = filteredData.length;
    loading.value = false;
  }, 500);
}

// 搜索
const handleQuery = () => {
  pagination.currentPage = 1
  fetchData()
}

// 重置搜索
// const handleReset = () => {
//   Object.keys(searchForm).forEach(key => {
//     if (key !== 'createTimeRange') {
//       searchForm[key] = ''
//     } else {
//       searchForm[key] = []
//     }
//   })
//   handleQuery()
// }
/** 重置按钮操作 */
const handleReset = () => {
  queryFormRef.value.resetFields()
  handleQuery()
}

// 切换展开状态
const toggleAdvancedSearch = () => {
  showAdvancedSearch.value = !showAdvancedSearch.value
}

// 表格选择
const handleSelectionChange = (selection) => {
  selectedRows.value = selection
}

// 分页变化
const handleSizeChange = (val) => {
  pagination.pageSize = val
  fetchData()
}

const handleCurrentChange = (val) => {
  pagination.currentPage = val
  fetchData()
}

// 操作按钮方法
const handleAdd = () => {
  currentBom.value = {}
  dialogVisible.value = true
}

const handleDelete = () => {
  ElMessageBox.confirm('确定要删除选中的数据吗?', '提示', {
    type: 'warning'
  }).then(() => {
    ElMessage.success('删除成功')
    fetchData()
  }).catch(() => {
    // 取消删除
  })
}

const handleApprove = () => {
  ElMessageBox.confirm('确定要审核选中的数据吗?', '提示', {
    type: 'warning'
  }).then(() => {
    ElMessage.success('审核成功')
    fetchData()
  }).catch(() => {
    // 取消审核
  })
}

const handleReject = () => {
  ElMessageBox.confirm('确定要反审核选中的数据吗?', '提示', {
    type: 'warning'
  }).then(() => {
    ElMessage.success('反审核成功')
    fetchData()
  }).catch(() => {
    // 取消反审核
  })
}

const handleImport = () => {
  // 导入逻辑
  ElMessage.info('导入功能待实现')
}

const handleExport = () => {
  // 导出逻辑
  ElMessage.info('导出功能待实现')
}

// 行操作
const handleCopy = (row) => {
  currentBom.value = { ...row, bomCode: '' }
}

// const handleDetail = (row) => {
//   // 查看详情逻辑
//   ElMessage.info(`查看详情: ${row.bomCode}`)
// }
const detailVisible = ref(false)
const currentDetail = ref(null)

// const handleDetail = async (id) => {
//   try {
//     loading.value = true
//     // 调用API获取详情
//     const res = await api.getBomDetail(id)
//     currentDetail.value = res.data
//     detailVisible.value = true
//   } catch (error) {
//     ElMessage.error('获取详情失败')
//   } finally {
//     loading.value = false
//   }
// }
// const handleDetail = (type: string, id?: number) => {
//   formRef.value.open(type, id)
// }

const handleDetail = (id: number) => {
  // 从模拟数据中获取详情
  currentDetail.value = mockData[id] || null
  detailVisible.value = true
}

const message = useMessage() // 消息弹窗
/** 行的导出按钮操作 */
const handleExportSingle = async () => {
  try {
    // 导出的二次确认
    await message.exportConfirm()
    // 发起导出
    exportLoading.value = true
    const data = await PurchaseReturnApi.exportPurchaseReturn(searchForm)
    download.excel(data, '标准BOM.xls')
  } catch {
  } finally {
    exportLoading.value = false
  }
}

const handlePrint = (row) => {
  // 打印逻辑
  ElMessage.info(`打印: ${row.bomCode}`)
  window.print(); // 调用浏览器打印
}
// const handlePrint = async (row) => {
//   try {
//     await row.printBOM(row.id); // 假设调用打印 API
//     ElMessage.success(`打印任务已发送: ${row.bomCode}`);
//   } catch (error) {
//     ElMessage.error("打印失败");
//   }
// };
// const handleDetail = (type: string, id?: number) => {
//   formRef.value.open(type, id)
// }

// 对话框提交
const handleDialogSubmit = (formData) => {
  dialogVisible.value = false
  // 这里是保存逻辑
  ElMessage.success('保存成功')
  fetchData()
}
</script>

<style scoped>
.bom-management-container {
  padding: 20px;
}

.search-card {
  margin-bottom: 20px;
}

.expand-link {
  margin-left: 20px;
}

.advanced-search {
  padding-top: 20px;
  margin-top: 20px;
  border-top: 1px solid #eee;
}

.operation-buttons {
  margin-bottom: 20px;
}

.pagination {
  display: flex;
  margin-top: 16px;
  text-align: right;
  justify-content: flex-end;
}

.el-table {
  margin-top: 20px;
}
</style>
